package ar.com.cema.methodology.analyzer.services.business.impl;

import java.util.Date;
import java.util.Set;
import java.util.TreeSet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ar.com.cema.methodology.analyzer.exceptions.PersonInformationException;
import ar.com.cema.methodology.analyzer.exceptions.SurveyAlreadyAnsweredException;
import ar.com.cema.methodology.analyzer.model.Person;
import ar.com.cema.methodology.analyzer.model.Question;
import ar.com.cema.methodology.analyzer.model.Survey;
import ar.com.cema.methodology.analyzer.services.business.SurveyBO;
import ar.com.cema.methodology.analyzer.services.repository.SimpleObjectRepository;
import ar.com.cema.methodology.analyzer.services.repository.SurveyRepository;

@Repository
public class SurveyBOImpl implements SurveyBO {
	
	@Autowired
	private SimpleObjectRepository simpleObjectRepository;
	
	@Autowired
	private SurveyRepository surveyRepository;
	
	@Override
	public Survey createEmptySurveyFor(Person person) {
		if (person.getEmail() == null || person.getEmail().isEmpty() ) {
			throw new PersonInformationException(person.getName() + " email field is incomplete.");
		}

		Survey aSurvey = surveyRepository.findSurveyFrom(person);

		if (aSurvey != null) {
			if (aSurvey.hasBeenAnswered()) {
				throw new SurveyAlreadyAnsweredException(person.getName() + " has already filled his survey. Can't do it again.");
			}
		} else {
			aSurvey = new Survey();
			aSurvey.setPerson(person);
			aSurvey.setQuestions(simpleObjectRepository.findAllWithAscendingOrder(Question.class));
			aSurvey = surveyRepository.save(aSurvey);
		}

		return aSurvey;
	}

	@Override
	public Survey save(Survey survey) {
		survey.setTimestamp(new Date()); // sets the timestamp for the answered survey
		return surveyRepository.update(survey);
	}

	@Override
	public Set<Person> listInterviewees() {
		Set<Person> personSet = new TreeSet<Person>();
		Set<Survey> surveys = simpleObjectRepository.findAll(Survey.class);
		
		for (Survey survey : surveys) {
			personSet.add(survey.getPerson());
		}
		
		return personSet;
	}
}